from flask import Flask, render_template, url_for, request
import random
app = Flask(__name__)

right=['坚持守法合规','坚持诚实守信','坚持专业精进', '坚持审慎稳健', '坚持长期理念' ,'坚持勤勉尽责', '坚持廉洁自律' ,'坚持珍惜声誉' ,'坚持服务实体', '坚持金融报国']
wrong=['反对违法乱纪', '反对背信弃义' ,'反对不思进取', '反对盲目扩张', '反对急工冒进', '反对玩忽职守', '反对拜金享乐' ,'反对损害形象', '反对脱实向虚' ,'反对自私自利']
global nanswer
global goal
goal=0
@app.route('/')
def hello_world():
    return render_template("index.html")

@app.route('/getscore', methods=['GET', 'POST'])
def getscore():
    if request.method == 'POST':
        data=[]
        data.append(int(request.form.get('a')))
        data.append(int(request.form.get('b')))
        data.append(int(request.form.get('c')))
        data.append(int(request.form.get('d')))
        global nanswer
        global goal
        if(nanswer==data):#验证前端选择的答案和后端保存的答案是否一致。
            goal=goal+1
        else:
            goal=goal-1
        rnum = random.randint(1, 4)
        wnum = 4 - rnum
        rindex = random.sample(range(len(right)), rnum)
        sample = []
        answer = []
        for i in rindex:
            sample.append(right[i])
            answer.append(1)
        if wnum != 0:
            windex = random.sample(range(len(right)), wnum)
            for i in windex:
                sample.append(wrong[i])
                answer.append(0)
        state = random.getstate()
        nsample = random.sample(sample, len(sample))
        random.setstate(state)
        nanswer = random.sample(answer, len(answer))#再次抽取题目，同时更新答案
        result = {'sample': nsample, 'rnum': rnum, 'answer': nanswer, 'goal': goal}
        return result
@app.route('/exam')
def exam():
    rnum = random.randint(1, 4)
    wnum = 4 - rnum
    rindex = random.sample(range(len(right)), rnum)#随机取正确答案rnum个下标
    sample=[]
    answer=[]
    for i in rindex:
        sample.append(right[i])
        answer.append(1)#正确答案数组，用于验证答案正确性
    if wnum != 0:
        windex = random.sample(range(len(right)), wnum)
        for i in windex:
            sample.append(wrong[i])
            answer.append(0)
    state=random.getstate()
    nsample=random.sample(sample, len(sample))#打乱选项样本
    random.setstate(state)
    global nanswer
    global goal
    nanswer=random.sample(answer, len(answer))#按照选项样本的打乱顺序，打乱答案，此时答案的0,1,和选项搭配。
    result={'sample':nsample,'rnum':rnum,'answer':nanswer,'goal':goal}
    return render_template("exam.html",result=result)



if __name__ == '__main__':
    app.run()
